package com.twu.biblioteca;

import com.twu.exception.ShelfException;

import java.util.ArrayList;
import java.util.HashMap;

public class BookShelf {

    private final HashMap<Book, Customer> lentBooks;
    private ArrayList<Book> books;
    public BookShelf(HashMap<Book, Customer> lentBooks) {
        this.books = new ArrayList<Book>();
        this.lentBooks = lentBooks;
    }

    public boolean containsExact(Book book) {
        if (books.contains(book)) {
            return true;
        }
        return false;
    }

    public void add(Book book) throws ShelfException {
        if (books.contains(book)) {
            throw new ShelfException(LibraryConstants.BOOK_IN_SHELF);
        }
        for (Book thisBook : books) {
            if (thisBook.number() == book.number()){
                throw new ShelfException(LibraryConstants.BOOK_WITH_NUMBER);
            }
        }
        books.add(book);
    }

    public boolean containsSimilar(Book book) {
        for (Book bookInList : books) {
            if (bookInList.title().equals(book.title()) && bookInList.author().equals(book.author())) {
                return true;
            }
        }
        return false;
    }

    public Book fetch(String title, String author) throws ShelfException {
        for (Book bookInList : books) {
            if (bookInList.title().equals(title) && bookInList.author().equals(author) && !lentBooks.containsKey(bookInList)) {
                return bookInList;
            }
        }
        throw new ShelfException(LibraryConstants.UNSUCCESSFUL_BOOK_CHECKOUT_MSG);
    }

    public Book returningBook(int number) throws ShelfException {
        for (Book bookInList : books) {
            if (bookInList.number() == number && lentBooks.containsKey(bookInList)) {
                return bookInList;
            }
        }
        throw new ShelfException(LibraryConstants.UNSUCCESSFUL_BOOK_CHECKOUT_MSG);
    }

    public String books() {
        String bookString = LibraryConstants.EMPTY_STRING;
        for (Book book : books) {
            if (!lentBooks.containsKey(book)) {
                bookString += book.title() + LibraryConstants.COMMA + book.author() + LibraryConstants.NEW_LINE;
            }
        }
        if (bookString.isEmpty()) {
            bookString += LibraryConstants.ALL_BOOKS_LENT_OUT_MSG;
        }
        return bookString;
    }
}
